<script setup lang="ts">
import { downloadDataset, shareDataset } from '@/api/data/datasetActions'; // 导入新的 API 函数
import { CalendarOutlined, DownloadOutlined, ShareAltOutlined, TeamOutlined } from '@ant-design/icons-vue'; // 导入图标
import { message } from 'ant-design-vue';
import { getIcon } from "@/api/assets/assets";
import { onMounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
// 定义 props 来接收传入的数据
const props = defineProps<{ app: Record<string, any> }>();
// 导入图片
// import imageUsrName from '@/assets/yhtx_dlzc_head2.png';
// import imageDownloadNum from '@/assets/31.png';

const imageUsrName = ref<string | null>(null);
const imageDownloadNum = ref<string | null>(null);

const fetchIcon = async () => {
  try {
    const data = await getIcon(['yhtx_dlzc_head2.png', '31.png']);
    imageUsrName.value = data['yhtx_dlzc_head2.png'];
    imageDownloadNum.value = data['31.png'];
  }
  catch (error) {
    console.error('API 调用错误:', error);
  }
};

const app = ref(props.app); // 接收传入的 app 数据
const collected = ref(false);
const liked = ref(false);
const downloads = ref(0);
const likes = ref(0);
const favorites = ref(0);
const views = ref(0);

// const route = useRoute();
const router = useRouter();

// 监听 app 的变化
watch(() => props.app, (newApp) => {
  // console.log('New app data received:', newApp);
  app.value = newApp; // 更新 app 数据
});

// 获取应用数据
onMounted(() => {
  // console.log('Initial App Data:', app.value);
  fetchIcon();
  downloads.value = Number(app.value.downloads || 0);
  likes.value = Number(app.value.likes || 0);
  favorites.value = Number(app.value.favorites || 0);
  views.value = Number(app.value.views || 0);
  collected.value = false;
  liked.value = false;
});

const handleClick = async () => {
  // console.log('Handle Click triggered for app:', app.value);
  views.value += 1;
  localStorage.setItem('selectedApp', JSON.stringify(app.value));
  // router.push(`datasquare/details/${app.value.datasetId}`);
  router.push({ name: "DataDetail", params: { datasetId: app.value.datasetId } });
};

const handleAction = async (action: 'download' | 'like') => {
  // console.log(`Handle action: ${action} for app:`, app.value);
  if (action === 'download') {
    try {
      const downloadLink = await downloadDataset(app.value.datasetId);
      // console.log('Download API Response:', downloadLink);
      downloads.value += 1;
      if (downloadLink)
        window.open(downloadLink, '_blank');
    }
    catch (error) {
      console.error('Error fetching download link:', error);
      message.error('下载失败，请稍后重试。');
    }
  }
  else if (action === 'like') {
    try {
      const response = await shareDataset(app.value.datasetId);
      // console.log('Like/Share API Response:', response);
      likes.value += 1;
      const shareLink = response.msg;
      if (shareLink) {
        await navigator.clipboard.writeText(shareLink);
        message.success('链接已复制到剪贴板');
      }
    }
    catch (error) {
      console.error('Error sharing dataset:', error);
      message.error('分享失败，请稍后重试。');
    }
  }
};
</script>

<template>
  <div class="data-item">
    <div class="card-top">
      <img :src="app.image" :alt="app.title" class="data-image">
      <div class="data-details">
        <div class="card-top-right">
          <h2>{{ app.title }}</h2>
        </div>
        <div v-if="app.tags.length > 0" class="tags">
          <span v-for="(tag, index) in app.tags.slice(0, 2)" :key="index" class="tag">{{ tag }}</span>
          <span v-if="app.tags.length > 3" class="tag">...</span>
        </div>
        <p class="description">
          {{ app.description }}
        </p>
      </div>
    </div>
    <div class="card-bottom">
      <div class="meta">
        <a-row>
          <a-col :span="16">
            <span>
              <div class="icon">
                <TeamOutlined />
              </div>
              <div class="word">
                {{ app.username }}
              </div>
            <!-- <a-avatar :src="imageUsrName" alt="用户名" :size="20" /> -->
            </span>
          </a-col>
          <a-col :span="7">
            <span>
              <div class="icon">
                <DownloadOutlined />
              </div>
              <div class="word">
                {{ downloads }}
              </div>
            <!-- <a-avatar :src="imageDownloadNum" alt="下载量" :size="20" /> -->
            </span>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="16">
            <span>
              <div class="icon">
                <CalendarOutlined />
              </div>
              <div class="word">
                {{ app.date }}
              </div>
            </span>
          </a-col>

          <!-- <span class="share-like" @click="handleAction('like')"> -->
          <a-col :span="7">
            <span>
              <div class="icon">
                <ShareAltOutlined />
              </div>
              {{ likes }}
            </span>
          </a-col>
        </a-row>
      </div>
      <div class="buttons-container">
        <button class="detail-button" @click="handleAction('download') ">
          下载数据
        </button>
        <button class="detail-button" @click="handleClick">
          查看详情
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.data-item {
  width: 90%; /* 760px */
  height: 20rem; /* 280px */
  border-radius: 1.25rem; /* 20px */
  margin-bottom: 1.25rem; /* 20px */
  display: flex;
  flex-direction: column;
  background-color: #fff;
  padding: 0.625rem; /* 10px */
  transition: transform 0.2s; /* 添加一个轻微的缩放效果 */
  cursor: default; /* 鼠标悬停在卡片上时不变 */
}

.card-top {
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 0.605rem; /* 10px */
  margin-top: 15px;

  .data-image {
    width: 7.375rem; /* 150px */
    height: 7.375rem; /* 150px */
    object-fit: cover;
    border-radius: 0.5rem; /* 8px */
    margin-right: 0.7375rem;
  }

  .data-details {
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .card-top-right {
      display: flex;
    }

    .card-top-right h2{
      font-size: 0.85rem;
      margin-right: 0.02rem;
    }

    .tags {
      display: flex;
      gap: 0.25rem; /* 10px */
      margin: 0.325rem 0; /* 10px 0 */

      .tag {
        background-color: #fff;
        color: black;
        border: 0.0625rem solid #ccc; /* 1px */
        border-radius: 0.25rem; /* 4px */
        padding: 0.3rem 0.2rem; /* 4px 5px */
        font-size: 0.6rem; /* 16px */
      }
    }

    .description {
    margin: 0;
    font-size: 0.7rem; /* 18px */
    color: #555;
    display: -webkit-box;
    -webkit-line-clamp: 2; /* 限制文本行数为三行 */
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    }

    .data-details h2 {
      margin-right: -0.9375rem; /* -15px */
      font-size: 1.2rem; /* 20px */
    }
  }
}

.favorites {
    flex-shrink: 0;
    padding: 0.1875rem 0.375rem; /* 3px 6px */
    margin-left: 0.625rem; /* 10px */
}

.card-bottom {
  flex: 1;
  display: flex;
  justify-content: space-between;
  flex-direction: column;
  align-items: center;
  padding: 0.605rem; /* 10px */
}

.meta {
    display: flex;
    flex-wrap: wrap;
    gap: 0.625rem; /* 10px */
    font-size: 0.8rem; /* 0.8em */
    justify-content:space-between;
    color: #888;
}

.icon {
  width: 2rem;
}

.word {
  width: 9rem;
}

.meta span {
    display: flex;
    width: 11rem;
    align-items: center;
    margin-right: 2rem; /* 40px */
}

.actions {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    gap: 0.625rem; /* 10px */
    width: 100%;
}

.favorites {
    display: flex;
    align-items: center;
    font-size: 0.7875rem; /* 0.9em */
    color: #333;
    border: 0.0625rem solid #ddd; /* 1px */
    border-radius: 0.9375rem; /* 15px */
    padding: 0.1875rem 0.375rem; /* 3px 6px */
    margin-right: -0.3125rem; /* -5px */
}

.favorites img {
    width: 0.9375rem; /* 15px */
    height: 0.9375rem; /* 15px */
    margin-right: 0.125rem; /* 2px */
    margin-top: -10%;
    vertical-align: middle;
}

.buttons-container {
  flex:1;
  display: flex;
  align-items: center;
  margin-top: 1rem;
  justify-content: space-around;
}

.detail-button {
    background-color: #e6f0ff;
    color: #2669f3;
    border: none;
    height: 2rem;
    padding: 8px 18px; /* 10px 20px */
    border-radius: 3px; /* 3px */
    margin-right: 1.3rem;
    cursor: pointer; /* 鼠标悬停在按钮上时变成小手 */
}

.detail-button:hover {
    background-color: #3867ea;
    color: #fff;
}
</style>
